#include "kernel/types.h"
#include "user/user.h"

#define MAXSIZE 36
#define PRIME '1'
#define NOT_PRIME '0'

void prime(int pipe_read, int pipe_write)
{
    char nums[MAXSIZE];
    read(pipe_read, nums, MAXSIZE);
    int first_prime = 0;
    for (int i = 0; i < MAXSIZE; i++)
    {
        if (nums[i] == PRIME)
        {
            first_prime = i;
            break;
        }
    }
    if (first_prime == 0)
    {
        exit(0);
    }
    // 输出语句，删除这个数
    printf("prime %d\n", first_prime);
    nums[first_prime] = NOT_PRIME;

    // 划掉倍数
    for (int i = first_prime; i < MAXSIZE; i++)
    {
        if (i % first_prime == 0)
        {
            nums[i] = NOT_PRIME;
        }
    }

    // 继续创建子进程
    int pid = fork();
    if (pid > 0)
    {
        write(pipe_write, nums, MAXSIZE);
        wait(0);
    }
    if (pid == 0)
    {
        prime(pipe_read, pipe_write);
    }
}

int main()
{
    int fd[2];
    pipe(fd);
    char nums[MAXSIZE];
    nums[0] = NOT_PRIME;
    nums[1] = NOT_PRIME;
    for (int i = 2; i < MAXSIZE; i++)
    {
        nums[i] = PRIME;
    }

    int pid = fork();
    if (pid > 0)
    {
        write(fd[1], nums, MAXSIZE);
        wait(0);
    }
    if (pid == 0)
    {
        prime(fd[0], fd[1]);
        wait(0);
    }
    exit(0);
}